from flask_socketio import Namespace, emit, disconnect, request
import requests
from stationpilot.servers.common.shared import mqtt_subscriptions,mq_client

# REST API 基础地址
REST_API_BASE = "http://localhost:5000"


class StationNamespace(Namespace):
    def on_connect(self):
        print(f"Client connected: {request.sid}")

    def on_disconnect(self):
        print(f"Client disconnected: {request.sid}")
        # 移除该客户端的所有订阅
        for topic, clients in list(mqtt_subscriptions.items()):
            if request.sid in clients:
                clients.remove(request.sid)
                if not clients:
                    mq_client.unsubscribe(topic)
                    del mqtt_subscriptions[topic]

    # def on_stations_list(self, message):
    #     """调用 REST API 获取所有 station"""
    #     request_id = message.get("request_id")
    #     try:
    #         resp = requests.get(f"{REST_API_BASE}/stations/list")
    #         data = resp.json()
    #         emit("stations:list_result", {
    #             "request_id": request_id,
    #             "stations": data
    #         })
    #     except Exception as e:
    #         emit("system:error", {
    #             "request_id": request_id,
    #             "code": 500,
    #             "message": str(e)
    #         })

    def on_stations_subscribe_summary(self, message):
        """订阅某个 station 的 summary"""
        station_id = message["station_id"]
        topic = f"/stations/summary/{station_id}"
        self._subscribe_topic(topic)

    def on_stations_unsubscribe_summary(self, message):
        """取消订阅 station summary"""
        station_id = message["station_id"]
        topic = f"/stations/summary/{station_id}"
        self._unsubscribe_topic(topic)

    def on_tests_subscribe(self, message):
        """订阅 test 数据"""
        station_id = message["station_id"]
        test_id = message["test_id"]
        topics = [
            f"/stations/test/{station_id}/{test_id}",
            f"/stations/test/phases/{station_id}/{test_id}"
        ]
        for topic in topics:
            self._subscribe_topic(topic)

    def on_tests_unsubscribe(self, message):
        """取消订阅 test 数据"""
        station_id = message["station_id"]
        test_id = message["test_id"]
        topics = [
            f"/stations/test/{station_id}/{test_id}",
            f"/stations/test/phases/{station_id}/{test_id}"
        ]
        for topic in topics:
            self._unsubscribe_topic(topic)

    # ========== 内部方法 ==========
    def _subscribe_topic(self, topic):
        if topic not in mqtt_subscriptions:
            mqtt_subscriptions[topic] = set()
            mq_client.subscribe(topic)
        mqtt_subscriptions[topic].add(request.sid)
        emit("system:subscribed", {"topic": topic})

    def _unsubscribe_topic(self, topic):
        if topic in mqtt_subscriptions and request.sid in mqtt_subscriptions[topic]:
            mqtt_subscriptions[topic].remove(request.sid)
            if not mqtt_subscriptions[topic]:
                mq_client.unsubscribe(topic)
                del mqtt_subscriptions[topic]
        emit("system:unsubscribed", {"topic": topic})
